<?php
/**
 * Created by PhpStorm.
 * User: lgradassi
 * Date: 13.09.14
 * Time: 02:12
 */

class RequireLogin extends CBehavior {

    public function attach($owner) {
        $owner->attachEventHandler('onBeginRequest', array($this, 'handleBeginRequest'));
    }

    public function handleBeginRequest($event)
    {
            // Handle the case without r in the get request
            if( (Yii::app()->user->isGuest) && (!isset($_GET['r']))) {
                Yii::app()->user->loginRequired();
            }
            if (Yii::app()->user->isGuest && !in_array($_GET['r'],array('site/login','site/locked'))) {
                Yii::app()->user->loginRequired();
            }

            // Check if the account is locked. If yes, logout
            if( (Yii::app()->user->isGuest) && (isset($_GET['r']))) {
                if (!Yii::app()->user->isGuest && !in_array($_GET['r'], array('site/login', 'site/locked'))) {
                    $user = User::model()->find('username=?', array(Yii::app()->user->id));
                    if ($user->locked == 1) {
                        Yii::app()->user->logout();
                        Yii::app()->user->loginRequired();
                    }
                }
            }
    }
}
?>